package main.java.LeetCode.ClassicalAlgorithm.RateLimit.Impl;

import main.java.LeetCode.ClassicalAlgorithm.RateLimit.RateLimit;

public class TokenBucket implements RateLimit {

    private final long capacity;
    private long beginTime;
    private final long duration;
    private long tokens;

    public TokenBucket(int granularity,long capacity){
        this.capacity = capacity;
        beginTime = System.currentTimeMillis();
        duration = 1000/granularity;
        tokens = 0;
    }
    @Override
    public synchronized boolean isLimit(long count) {
        long now = System.currentTimeMillis();
        tokens = Math.min(capacity,tokens+(now-beginTime)/duration);
        beginTime = now;
        return count>=tokens;
    }
}
